<?php

namespace app\admin\controller\benefit;

use app\Request;
use think\App;
use think\response\Json;
use think\facade\Cache;
use app\common\controller\AdminController;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;
use app\admin\service\TriggerService;

#[ControllerAnnotation(title: '效益计算参数设置')]
class Config extends AdminController
{
    private array $notes;

    #[NodeAnnotation(ignore: ['add', 'delete', 'edit', 'export', 'modify', 'recycle'])]
    protected array $ignoreNode;

    private array $month_type = [
        ['name' => '上月', 'value' => '0'],
        ['name' => '本月', 'value' => '1'],
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        self::$model = new \app\admin\model\BenefitConfig();
        $notes = self::$model::$notes;

        $this->notes = $notes;
        $this->assign(compact('notes'));
    }

    #[NodeAnnotation(title: '列表', auth: true)]
    public function index(Request $request): Json|string
    {
        $this->assign('monthTypeArray', $this->month_type);
        $this->assign('monthType', benefitConfig('calculate_month_type'));
        return $this->fetch();
    }

    #[NodeAnnotation(title: '保存', auth: true)]
    public function save(Request $request): void
    {
        $this->checkPostRequest();
        $post  = $request->post();
        try {
            foreach ($post as $key => $val) {
                if (self::$model::where('name', $key)->count()) {
                    self::$model::where('name', $key)->update(['value' => $val,]);
                } else {
                    self::$model::create(
                        [
                            'name'  => $key,
                            'value' => $val,
                        ]
                    );
                }
                if (Cache::has($key)) Cache::set($key, $val);
            }
            TriggerService::updateBenefitConfig();
        } catch (\Exception $e) {
            $this->error(config("code.operation_failed") . $e->getMessage());
        }
        $this->success(config("code.operation_success"));
    }
}
